import VueRouter from 'vue-router'
import Vue from 'vue'
// 引入axios
// import axios from 'axios'

// 引入子组件
import login from '../components/login/login.vue'
import home from '../components/home/home.vue'
import users from '../components/users/users.vue'
import roles from '../components/roles/roles.vue'
import rights from '../components/rights/rights.vue'
import categories from '../components/categories/categories.vue'
import goods from '../components/goods/goods.vue'
import addGood from '../components/add-good/add-good.vue'

// 再模块化工程中，要用Vue.use()
Vue.use(VueRouter)

// 重写路由的push方法,这样router从 /xx 导航到相同的 /xx就不会报错了
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}

const router = new VueRouter({
  routes: [
    // 重定向
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/home',
      name: 'home',
      component: home,
      // 嵌套路由测试
      children: [
        {
          path: '/users/:pagenum?',
          component: users
        },
        {
          path: '/roles',
          component: roles
        },
        {
          path: '/rights',
          component: rights
        },
        {
          path: '/categories',
          component: categories
        },
        {
          path: '/goods',
          component: goods
        },
        {
          path: '/add-good',
          component: addGood
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  // console.log(from)
  // console.log(to)

  // console.log(localStorage.getItem('token'))

  // console.log(localStorage.getItem('token'))
  if (to.path === '/login') {
    next()
  } else {
    const token = localStorage.getItem('token')
    token ? next() : next('/login')
    // next('/xxx') 可以看作时一个循环的，/xxx依然会进入这里的守卫进行判断
  }
})

export default router
